Component({
  options: {
    multipleSolts: true //定义组件支持多solts
  },
  /*
   * 组件的属性列表 
   */
  properties: {
    //提示语
    hint: {
      type: String,
      value: "添加图片"
    },
    //提示icon
    /* 
     * 默认支持的icon类有10种
     * 相机
     * iconfont icon-xiangji
     * iconfont icon-xiangji1
     * iconfont icon-xiangji2
     * iconfont icon-xiangji3
     * iconfont icon-camera_full
     * 添加
     * iconfont icon-tianjia
     * iconfont icon-tianjia1
     * iconfont icon-tianjia2
     * iconfont icon-tianjia3
     * iconfont icon-icontjzp
     */
    hint_icon: {
      type: String,
      value: "iconfont icon-xiangji"
    },
    icon_size: {
      type: String,
      value: "100rpx"
    },
    icon_color: {
      type: String,
      value: "#2C2C2C"
    },
    //提示块的背景颜色
    hint_background: {
      type: String,
      value: "#E5E5E5"
    },
    //每块的高 高宽比默认1:1
    hint_height: {
      type: String,
      value: "160rpx"
    },
    //每块的宽 高宽比默认1:1
    hint_width: {
      type: String,
      value: "160rpx"
    },
    //整体背景颜色
    background: {
      type: String,
      value: "#FFFFFF"
    },
    //图片剪裁mode
    mode: {
      type: String,
      value: "aspectFill"
    }

  },
  //内部数据
  data: {
    imgWidth: 0,
    imgHeight: 0,
    image: [],
    maxCnt:6,
    currentCnt: 0
  },
  //组件方法列表
  methods: {
    //加载启事的图片
    loadImageEvent: function (tempFilePaths) {
      var that = this;
      console.log('调用自定义组件函数', tempFilePaths);
      that.getCanvasImg(0, 0, tempFilePaths); //进行压缩

      that.triggerEvent('sureImageUpload', that.data.image);

    },
    // 上传图片
    chooseImage: function (e) {
      var that = this;

      wx.chooseImage({
        count: that.data.maxCnt,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          console.log(res.tempFilePaths)
          var tempFilePaths = res.tempFilePaths; //用户选择的图片的本地路径列表
          var length = tempFilePaths.length //用户选了几张
          var obj = {};
          if (that.data.image.length >= that.data.maxCnt) {
            wx.showToast({
              title: '图片最多上传6张',
              icon: 'none',
              duration: 2000,
              mask: true
            });
            return false;
          }
          
          
          //将路径循环push入image数组中
          // var i = 0
          // while (length) {

          //   var obj = {};


          //   that.data.image.push(obj);
          //   length--
          //   i++
          // }
          that.getCanvasImg(0, 0, tempFilePaths); //进行压缩


          //var myEventDetail = e; // detail对象，提供给事件监听函数
          //var myEventOption = {}; // 触发事件的选项
          that.triggerEvent('sureImageUpload', that.data.image)
        },
        fail: function () {

        }
      })
    },
    // 删除图片
    removeImage: function (event) {

      //删除相应的数组元素
      this.data.image.splice(event.currentTarget.id, 1)
      //重新渲染视图
      this.setData({
        image: this.data.image,
        currentCnt:this.data.currentCnt-1
      })
    },
    //压缩并获取图片，这里用了递归的方法来解决canvas的draw方法延时的问题
    getCanvasImg: function (index, failNum, tempFilePaths) {
      var that = this;
      //console.log(tempFilePaths)
      if (index < tempFilePaths.length) {
        if (that.data.image.length >= that.data.maxCnt) {
          wx.showToast({
            title: '图片最多上传6张',
            icon: 'none',
            duration: 2000,
            mask: true
          });
          return false;
        }
        const ctx = wx.createCanvasContext('firstCanvas', that);
        wx.getImageInfo({
          src: tempFilePaths[index],
          success(res) {
            console.log(res)

            // 图片原始尺寸
            let originWidth = res.width;
            let originHeight = res.height;
            // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
            let maxWidth = 1200,
              maxHeight = 800;
            // 目标尺寸
            let targetWidth = originWidth,
              targetHeight = originHeight;
            // 图片尺寸超过200x150的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽，按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
            }
            // canvas对图片进行缩放
            that.setData({
              imgWidth: targetWidth,
              imgHeight: targetHeight
            })


            // 压缩图片（绘制图像到画布）
            ctx.drawImage(res.path, 0, 0, targetWidth, targetHeight);

            ctx.draw(false, () => {
              index = index + 1;
              setTimeout(function () {
                // canvas导出为图片路径
                wx.canvasToTempFilePath({
                  canvasId: 'firstCanvas',
                  fileType: 'jpg', //支持jpg或png
                  quality: 0.92, //图片质量
                  success(res) {
                    console.log(res)
                    //let path = res.tempFilePath;
                    var obj = {};
                    obj.imageHide = "";
                    obj.imageAddress = res.tempFilePath;
                    that.data.image.push(obj);
                    that.getCanvasImg(index, failNum, tempFilePaths);
                    console.log(that.data.image)
                    //使body自适应图片的增加
                    var l = that.data.image.length
                    if (l >= 3) {
                      var b = parseInt(l / 3)
                      that.setData({
                        bodyStyle: "height:" + (328 + b * 90) + "px"
                      })
                    }
                    //重新渲染image视图
                    that.setData({
                      image: that.data.image
                    });
                  },
                  fail(err) {
                    console.log(err);
                  }
                }, that);
              }, 50);
            });
          }
        });
      }
    }
  }

})